using System;
using System.Web;
using System.Web.UI;
using ASPNETVN.PORTAL.Components.Configuration;
using ASPNETVN.PORTAL.Components.Configuration.Items;
using ASPNETVN.PORTAL.Components.Helpers;

namespace ASPNETVN.PORTAL.Controls
{
    public partial class Search : UserControl
    {

        protected static string GetUrl(int moduleID, int itemID)
        {
            int tabID = 0;
            int tabIndex = 0;
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();
            Components.Configuration.Items.Portal portal = (Components.Configuration.Items.Portal)HttpContext.Current.Items["Portal"];
            foreach (Tab tab in portal.Tabs)
            {
                PortalDataSet.TabRow activeTab = ds.Tab.FindByID(tab.ID);
                foreach (PortalDataSet.ModuleRow moduleRow in activeTab.GetModuleRows())
                {
                    if (moduleRow.ID == moduleID)
                    {
                        tabID = tab.ID;
                        tabIndex = tab.Index;
                        goto Next;
                    }
                }
            }
        Next:
            return string.Format("~/Default.aspx?tabIndex={0}&tabID={1}&Page=Detail&ItemID={2}", tabIndex, tabID, itemID);
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                if (Request.QueryString["value"] != null)
                {
                    txtSearchText.Text = Server.UrlDecode(Request.QueryString["value"]);
                    string searchText = Server.UrlDecode(Request.QueryString["value"]);
                    dlItems.DataSource = SearchHelper.Search(searchText);
                    dlItems.DataBind();
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("~/Search.aspx?value={0}", Server.UrlEncode(txtSearchText.Text.Trim())));
        }

        protected void dlItems_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                string[] s = e.CommandArgument.ToString().Split(';');
                Response.Redirect(GetUrl(Convert.ToInt32(s[0]), Convert.ToInt32(s[1])));
            }
        }
    }
}